package com.liuyi.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.liuyi.dao.UserDao;
import com.liuyi.service.UserService;
import com.liuyi.util.CommonUtil;
import com.liuyi.util.GetLoginInstitution;
import com.liuyi.util.constants.ErrorEnum;

import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;

/**
 * @author: cd
 * @description: 用户/角色/权限
 * @date: 2018/03/19 10:18
 */
@Service
public class UserServiceImpl implements UserService {
	
    @Autowired
    private UserDao userDao;

    /**
     * 用户列表
     *
     * @param jsonObject
     * @return
     */
    @Override
    public JSONObject listUser(JSONObject jsonObject) {
        CommonUtil.fillPageParam(jsonObject);
        JSONObject userInfo = (JSONObject) SecurityUtils.getSubject().getSession().getAttribute("userInfo");
        jsonObject.put("identity", userInfo.getString("identity"));
        //获取到当前登入人的机构id
        String institution = GetLoginInstitution.getInstitution(userDao);
    	jsonObject.put("institution", institution);
    	int count = userDao.countUser(jsonObject);
        List<JSONObject> list = userDao.listUser(jsonObject);
        return CommonUtil.successPage(jsonObject, list, count);
    }

    /**
     * 添加用户
     *
     * @param jsonObject
     * @return
     */
    @Override
    public JSONObject addUser(JSONObject jsonObject) {
        int exist = userDao.queryExistUsername(jsonObject);
        if (exist > 0) {
            return CommonUtil.errorJson(ErrorEnum.E_10009);
        } 
        //获取到当前登入人的机构id
        String identity = GetLoginInstitution.getInstitution(userDao);
        jsonObject.put("identity", identity);
        jsonObject.put("icon", "http://media.guizong.org/20180515151248_");
        userDao.addUser(jsonObject);
        return CommonUtil.successJson();
    }

    /**
     * 查询所有的角色
     * 在添加/修改用户的时候要使用此方法
     *
     * @return
     */
    @Override
    public JSONObject getAllRoles() {
    	//获取到当前登入人的机构id
    	String institution = GetLoginInstitution.getInstitution(userDao);
        List<JSONObject> roles = userDao.getAllRoles(institution);
        return CommonUtil.successPage(roles);
    }

    /**
     * 修改用户
     * @param jsonObject
     * @return
     */
    @Override
    public JSONObject updateUser(JSONObject jsonObject) {
        userDao.updateUser(jsonObject);
        return CommonUtil.successJson();
    }

	@Override
	public JSONObject deleteUser(JSONObject jsonObject) {
		userDao.deleteUser(jsonObject);
        return CommonUtil.successJson();
	}
    
    /**
     * 角色列表
     *
     * @return
     */
    @Override
    public JSONObject listRole() {
    	JSONObject userInfo = (JSONObject) SecurityUtils.getSubject().getSession().getAttribute("userInfo");
        String identity = userInfo.getString("identity");
        String status = identity;
    	//获取到当前登入人的机构id
    	String institution = GetLoginInstitution.getInstitution(userDao);
        List<JSONObject> roles = userDao.listRole(institution,status);
        return CommonUtil.successPage(roles);
    }

    /**
     * 查询所有权限, 给角色分配权限时调用
     *
     * @return
     */
    @Override
    public JSONObject listAllPermission() {
    	List<JSONObject> permissions = new ArrayList<JSONObject>();
    	JSONObject userInfo = (JSONObject) SecurityUtils.getSubject().getSession().getAttribute("userInfo");
    	if ("1".equals(userInfo.getString("identity"))){
    		 permissions = userDao.listAllPlatformPermission();
    	} else {
    		 permissions = userDao.listAllPermission();
    	}
        return CommonUtil.successPage(permissions);
    }

    /**
     * 添加角色
     *
     * @param jsonObject
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public JSONObject addRole(JSONObject jsonObject) {
    	JSONObject userInfo = (JSONObject) SecurityUtils.getSubject().getSession().getAttribute("userInfo");
        String identity = userInfo.getString("identity");
        if (identity.equals("1")) {
        	jsonObject.put("status", "1");
        }else {
        	jsonObject.put("status", "0");
        }
    	jsonObject.put("superAdmin", "2");
        userDao.insertRole(jsonObject);
        userDao.insertRolePermission(jsonObject.getString("roleId"), (List<Integer>) jsonObject.get("permissions"));
        return CommonUtil.successJson();
    }

    /**
     * 修改角色
     *
     * @param jsonObject
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public JSONObject updateRole(JSONObject jsonObject) {
        String roleId = jsonObject.getString("roleId");
        List<Integer> newPerms = (List<Integer>) jsonObject.get("permissions");
        JSONObject roleInfo = userDao.getRoleAllInfo(jsonObject);
        Set<Integer> oldPerms = (Set<Integer>) roleInfo.get("permissionIds");
        //修改角色名称
        dealRoleName(jsonObject, roleInfo);
        //添加新权限
        saveNewPermission(roleId, newPerms, oldPerms);
        //移除旧的不再拥有的权限
        removeOldPermission(roleId, newPerms, oldPerms);
        return CommonUtil.successJson();
    }

    /**
     * 修改角色名称
     *
     * @param paramJson
     * @param roleInfo
     */
    private void dealRoleName(JSONObject paramJson, JSONObject roleInfo) {
        String roleName = paramJson.getString("roleName");
        if (!roleName.equals(roleInfo.getString("roleName"))) {
            userDao.updateRoleName(paramJson);
        }
    }

    /**
     * 为角色添加新权限
     *
     * @param newPerms
     * @param oldPerms
     */
    private void saveNewPermission(String roleId, Collection<Integer> newPerms, Collection<Integer> oldPerms) {
        List<Integer> waitInsert = new ArrayList<>();
        for (Integer newPerm : newPerms) {
            if (!oldPerms.contains(newPerm)) {
                waitInsert.add(newPerm);
            }
        }
        if (waitInsert.size() > 0) {
            userDao.insertRolePermission(roleId, waitInsert);
        }
    }

    /**
     * 删除角色 旧的 不再拥有的权限
     *
     * @param roleId
     * @param newPerms
     * @param oldPerms
     */
    private void removeOldPermission(String roleId, Collection<Integer> newPerms, Collection<Integer> oldPerms) {
        List<Integer> waitRemove = new ArrayList<>();
        for (Integer oldPerm : oldPerms) {
            if (!newPerms.contains(oldPerm)) {
                waitRemove.add(oldPerm);
            }
        }
        if (waitRemove.size() > 0) {
            userDao.removeOldPermission(roleId, waitRemove);
        }
    }

    /**
     * 删除角色
     *
     * @param jsonObject
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public JSONObject deleteRole(JSONObject jsonObject) {
        JSONObject roleInfo = userDao.getRoleAllInfo(jsonObject);
        List<JSONObject> users = (List<JSONObject>) roleInfo.get("users");
        if (users != null && users.size() > 0) {
            return CommonUtil.errorJson(ErrorEnum.E_10008);
        }
        userDao.removeRole(jsonObject);
        userDao.removeRoleAllPermission(jsonObject);
        return CommonUtil.successJson();
    }

    /**
     * 根据用户id查询机构
     * @Title: selectInstitutionById 
     * @Description: TODO
     * @param userId
     * @return
     * @return: String
     */
    @Override
	public String selectInstitutionById(Integer userId) {
		// TODO Auto-generated method stub
		return userDao.selectInstitutionById(userId);
	}

}
